import pymysql
from backend.config.db_config import DB_CONFIG

# 数据库配置
print("正在连接到数据库并添加菜品数据...")

try:
    # 连接到数据库
    conn = pymysql.connect(
        host=DB_CONFIG['host'],
        user=DB_CONFIG['user'],
        password=DB_CONFIG['password'],
        database=DB_CONFIG['database'],
        port=DB_CONFIG['port']
    )
    cursor = conn.cursor()
    print("成功连接到数据库！")
    
    # 准备菜品数据
    sample_foods = [
        {'food_name': '香辣小龙虾', 'price': 88.00, 'stock': 100, 'description': '精选小龙虾，香辣可口', 'category': '海鲜'},
        {'food_name': '烧烤羊肉串', 'price': 45.00, 'stock': 200, 'description': '正宗新疆羊肉串', 'category': '烧烤'},
        {'food_name': '炸鸡排', 'price': 18.00, 'stock': 150, 'description': '外酥里嫩，口感极佳', 'category': '油炸'},
        {'food_name': '炒米粉', 'price': 15.00, 'stock': 120, 'description': '新疆炒米粉，香辣过瘾', 'category': '主食'},
        {'food_name': '奶茶', 'price': 12.00, 'stock': 180, 'description': '珍珠奶茶，甜而不腻', 'category': '饮品'}
    ]
    
    # 检查food表是否存在
    cursor.execute("SHOW TABLES LIKE 'food'")
    if not cursor.fetchone():
        print("错误：food表不存在！")
        exit(1)
    
    # 插入菜品数据
    print(f"准备插入 {len(sample_foods)} 条菜品数据...")
    for food in sample_foods:
        sql = """INSERT INTO food (food_name, price, stock, description, category) 
                VALUES (%s, %s, %s, %s, %s)"""
        cursor.execute(sql, (
            food['food_name'], 
            food['price'], 
            food['stock'], 
            food['description'], 
            food['category']
        ))
    
    # 提交事务
    conn.commit()
    print(f"成功添加 {cursor.rowcount} 条菜品数据！")
    
    # 查询添加的菜品数据进行验证
    cursor.execute("SELECT food_id, food_name, price FROM food LIMIT 10")
    foods = cursor.fetchall()
    print("\n数据库中的菜品数据：")
    for food in foods:
        print(f"菜品ID: {food[0]}, 名称: {food[1]}, 价格: {food[2]}")
    
    print("\n请重新启动后端服务后刷新页面尝试获取菜品数据。")
    
except Exception as e:
    print(f"操作失败: {str(e)}")
    import traceback
    traceback.print_exc()
finally:
    if 'cursor' in locals():
        cursor.close()
    if 'conn' in locals():
        conn.close()